/**
 * Created by Dalyn on 2017/5/8.
 */
import React from "react";
import ReactDOM from 'react-dom';
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import EventManager from "../../../../../util/EventManager"
import { Table,Button,Icon,Modal,message,Input } from 'antd';
import ReactKey from "../../../../../util/ReactKey";
import Util from "../../../../../util/Util";
import AddMaterielModal from "./AddMaterielModal"
import BatchHint from "./BatchHint"
import DeleteMaterielBillMutation from './mutation/DeleteMaterielBillMutation';
import PurchMaterielBillMutation from './mutation/PurchMaterielBillMutation';
import FindMaterielBillMutation from '../../../createOrder/mutation/FindMaterielBillMutation';
import "./css/materielBom.css";

export default class MaterielBill extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            pageSize: 1000,
            pageNum: 1,
            dataSource:[],
            orderGoodsList:[],
            orderId:"",
            loading:false,
            //materielBillData:[],
            selectedRowKeys:[],
            selectedRows:[],
            filteredInfo: null,
            sortedInfo: null,
            bomId: "",
            //搜索
            filterDropdownVisible: false,
            searchText: '',
            filtered: false,
        };
        this.purchStatusObj={
            "0":"未采购",
            "1":"已采购",
        };
        this.materielTypeObj={
            "1":"面料",
            "2":"缝制辅料",
            "3":"包装辅料",
        };
        this.filtersArr = [];
        this.orderGoodsList = [];
        this.messageFlag = true;
        this.dataSource = [];
    }

    componentWillMount(){
        /*给body动态添加类名*/
        let body = document.getElementsByTagName("body")[0];
        Util.addClass(body,"table_filter");
        /*EventManager.on('removeBodyClass',(params)=>{
            switch (params){
                case "table_filter":
                    console.log(123);
                    // document.getElementById("myDIV").classList.add("table_filter_materiel");
                    document.getElementsByTagName("body")[0].className = "";
                    break;
            }
        });*/
        let {pageSize,pageNum} = this.state;
        this.findMaterielBill(pageSize,pageNum);
    }
    componentWillUnmount(){
        //动态移除类名
        document.getElementsByTagName("body")[0].className = "";
        // EventManager.emitter('removeBodyClass',"table_filter");
    }
    /*拉取表格数据*/
    findMaterielBill(pageSize,pageNum) {
        Relay.Store.commitUpdate(
            new FindMaterielBillMutation({
                pageSize:pageSize,
                pageNum: pageNum,
                orderId:this.props.orderId,
                isSearchAllStyleByOrder:1,//拉取订单全部款号
            }),
            {
                onFailure: () => {
                    message.error("网络请求失败")
                    this.setState({
                        loading: false
                    })
                },
                onSuccess: (response) => {
                    let errorCode = response.findMaterielBill.findMaterielBill.errorCode;
                    let value = response.findMaterielBill.findMaterielBill.value;
                    if (errorCode == 0) {
                        let materielBillList = response.findMaterielBill.findMaterielBill.materielBillList;
                        let orderGoodsList = response.findMaterielBill.findMaterielBill.orderGoodsList;
                        this.orderGoodsList = orderGoodsList;
                        orderGoodsList && orderGoodsList.map((v,i)=>{
                            this.filtersArr.push({text:v.styleNo, value: v.styleNo})
                        });
                        // console.log(orderGoodsList);
                        this.dataSource = materielBillList;
                        this.setState({
                            dataSource: materielBillList,
                            loading: false,
                            selectedRowKeys: [],
                            selectedRows: [],
                        })
                    } else{
                        this.setState({
                            loading: false
                        });
                        if(errorCode == 500){
                            message.error('服务器错误，请联系系统管理员')
                        }else {
                            message.error(value)
                        }
                    }
                }

            }
        );
    }
    /*删除请求*/
    deleteMaterielBill(){
        Relay.Store.commitUpdate(
            new DeleteMaterielBillMutation({
                bomIds: this.state.selectedRowKeys.join(","),
                orderId: this.props.orderId,
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let errorCode = response.deleteMaterielBill.deleteMaterielBill.errorCode;
                    let value = response.deleteMaterielBill.deleteMaterielBill.value;
                    if (errorCode === "0") {
                        message.success("删除成功");
                        this.findMaterielBill(1000,1);
                    } else {
                        let this_ = this;
                        if(errorCode == 500){
                            Util.messageHint(this_,"error","服务器错误，请联系系统管理员");
                        }else if(errorCode == 9999){
                            Util.messageHint(this_,"error","系统错误，请联系系统管理员");
                        }else {
                            Util.messageHint(this_,"error",value);
                        }

                    }
                }
            }
        );
    }
    /*标记为采购*/
    purchMaterielBill(){
        Relay.Store.commitUpdate(
            new PurchMaterielBillMutation({
                bomIds: this.state.selectedRowKeys.join(","),
                orderId: this.props.orderId,
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let errorCode = response.purchMaterielBill.purchMaterielBill.errorCode;
                    let value = response.purchMaterielBill.purchMaterielBill.value;
                    if (errorCode === "0") {
                        message.success("标记成功");
                        this.findMaterielBill(1000,1);
                    } else {
                        let this_ = this;
                        if(errorCode == 500){
                            Util.messageHint(this_,"error","服务器错误，请联系系统管理员");
                        }else if(errorCode == 9999){
                            Util.messageHint(this_,"error","系统错误，请联系系统管理员");
                        }else {
                            Util.messageHint(this_,"error",value);
                        }

                    }
                }
            }
        );
    }
    /*操作按钮*/
    editMateriel(type){
        let this_ = this;
        let {selectedRowKeys,selectedRows} = this.state;
        let flag = this.refs.addMaterielBill.state.visible;
        let params = {};
        switch (type){
            case "produceList":
                let select_orderType = '';
                if(!selectedRowKeys||selectedRowKeys.length<1){
                    Util.messageHint(this_,"error","请勾选要操作的物料");
                    return
                }
                if(selectedRows){
                    select_orderType = selectedRows[0].orderType;
                    selectedRows.map((v,i)=>{
                        if(select_orderType != v.orderType){
                            select_orderType = null;
                        }
                    });
                }else {
                    Util.messageHint(this_,"error","请勾选要操作的物料");
                    return
                }
                if(!select_orderType){
                    let message = "不同类型的物料，请分开采购";
                    Util.messageHint(this_,"error",message);
                    return
                }
                params.message = "确认要将该"+selectedRowKeys.length+"款物料生成采购订单吗？";
                params.operateType = "produceList";
                this.refs.batchHint.showConfirmModal(true,params);
                break;
            case "add":
                this.refs.addMaterielBill.setState({
                    confirmType:"add",
                },this.refs.addMaterielBill.showWindow(flag));
                break;
            case "edit":
                if(!selectedRowKeys||selectedRowKeys.length<1){
                    Util.messageHint(this_,"error","请勾选要操作的物料");
                    return
                }
                if(selectedRowKeys&&selectedRowKeys.length>1){
                    Util.messageHint(this_,"error","只可对单条物料进行编辑");
                    return
                }
                this.refs.addMaterielBill.setState({
                    saveMaterielBill:JSON.parse(JSON.stringify(selectedRows[0])),
                    confirmType:"edit",
                },this.refs.addMaterielBill.showWindow(flag));
                break;
            case "delete":
                if(!selectedRowKeys||selectedRowKeys.length<1){
                    Util.messageHint(this_,"error","请勾选要操作的物料");
                    return
                }
                params.message = "确定删除么？";
                params.operateType = "delete";
                this.refs.batchHint.showConfirmModal(true,params);
                break;
            case "markPurchase":
                if(!selectedRowKeys||selectedRowKeys.length<1){
                    Util.messageHint(this_,"error","请勾选要操作的物料");
                    return
                }
                params.message = "一旦标记该物料将无法进行操作，确定要标记为已采购吗？";
                params.operateType = "markPurchase";
                this.refs.batchHint.showConfirmModal(true,params);
                break;
        }
    }
    /*添加物料*/
    addMaterielSuccess(){
        message.success("添加成功");
    }
    /*点击筛选回调*/
    handleChange = (pagination, filters, sorter) => {
        // console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            selectedRowKeys: [],
        });
    };
    /*标记采购-确认按钮*/
    clickConfirm(type){
        let this_= this;
        let {selectedRowKeys,selectedRows} = this.state;
        switch (type){
            case "produceList":
                let select_orderType = selectedRows[0].orderType;
                let createType = {
                    1:"createordergms",
                    2:"createorderraw",
                    3:"createordercloth",
                    4:"createorderprint",
                    5:"createorderyarn",
                };
                if(select_orderType){
                    // console.log(selectedRows);
                    let goods = JSON.parse(JSON.stringify(selectedRows));
                    goods.map((v,i)=>{
                        v.colour = selectedRows[i].color;
                        v.quantity = selectedRows[i].needCount
                    });
                    if(select_orderType == 2){//跳转-新建辅料
                        EventManager.emitter('jumptab',"addMateriel_raw");
                    }else if(select_orderType == 3){//跳转-新建面料
                        EventManager.emitter('jumptab',"addMateriel_cloth");
                    }
                    hashHistory.push({pathname:'/creatorderbystep/',state:{
                        "name":createType[select_orderType],
                        "fromEdit":"addMateriel",
                        // 'enquiryId':this.props.enquiryId,
                        'parentId':this.props.orderId,
                        'partAName':this.props.partAName,
                        'account':this.props.account,
                        'goods':goods,
                    }});
                }else {

                }

                break;
            case "delete":
                this.deleteMaterielBill();
                break;
            case "markPurchase":
                this.purchMaterielBill();
                break;
        }
    }

    /*表格-款号-搜索*/
    onInputChange = (e) => {
        this.setState({ searchText: e.target.value });
    };
    onSearch = () => {
        const { searchText,dataSource } = this.state;
        const  dataSourceSelf = JSON.parse(JSON.stringify(this.dataSource));
        const reg = new RegExp(searchText, 'gi');
        //console.log("reg",reg);
        this.setState({
            filterDropdownVisible: false,
            filtered: !!searchText,
            dataSource: dataSourceSelf.map((record) => {
                const match = record.styleNo.toString().match(reg);
                //console.log("match",match);
                if (!match) {
                    return null;
                }
                return {
                    ...record,
                    styleNo: (
                        <span>
                          {record.styleNo.toString().split(reg).map((text, i) => (
                              i > 0 ? [<span className="highlight">{match[0]}</span>, text] : text
                          ))}
                        </span>
                    ),
                };
            }).filter(record => !!record),
        });
    };
    filterSearch(){
        this.setState({
            filterDropdownVisible:true,
        },() => this.searchInput.focus())
    }
    render(){
        // console.log(this.orderGoodsList);
        let {orderStatus} = this.props;
        let { dataSource,selectedRowKeys,selectedRows,sortedInfo, filteredInfo} = this.state;
        filteredInfo = filteredInfo || {};
        const columns = [
            {
                title: '状态',
                dataIndex: 'purchStatus',
                key: 'purchStatus',
                width:80,
                filters: [
                    { text: '未采购', value: '0' },
                    { text: '已采购', value: '1' },
                ],
                filteredValue: filteredInfo.purchStatus || null,
                onFilter: (value, record) =>{
                    return record.purchStatus.toString().includes(value)
                } ,
                filterMultiple:true,
                render: ((text, record, index) =>{
                    return <span ref={"purchStatus"}>{this.purchStatusObj[record.purchStatus]}</span>
                })
            },
            {
                title: '物料类型',
                dataIndex: 'materielType',
                key: 'materielType',
                width: 100,
                filters: [
                    { text: '面料', value: '1' },
                    { text: '缝制辅料', value: '2' },
                    { text: '包装辅料', value: '3' },
                ],
                filteredValue: filteredInfo.materielType || null,
                onFilter: (value, record) =>{
                    return record.materielType.toString().includes(value)
                } ,
                filterMultiple:true,
                render: ((text, record, index) =>{
                    return <span>{this.materielTypeObj[record.materielType]}</span>
                })
            },
            {
                title:"款号",
                dataIndex: 'styleNo',
                key: 'styleNo',
                width:100,
                filters: this.filtersArr,
                filteredValue: filteredInfo.styleNo || null,
                onFilter: (value, record) =>{
                    //console.log(value);
                    // return record.styleNo.match(value);//模糊匹配
                    return record.styleNo == value;//精确匹配
                } ,
                filterMultiple:true,
                render:(text, record, index) =>{
                    return <span className="" ref={"styleNo"}>{record.styleNo}</span>
                }
            },
            /*{
                title:<span className="table-filter-styleNo-span">款号<Icon type="search" className="table-filter-search-icon" style={{ color: this.state.filtered ? '#36b3b3' : '#aaa' }} onClick={this.filterSearch.bind(this)}/></span>,
                dataIndex: 'styleNo',
                key: 'styleNo',
                className:"table-filter-styleNo",
                filterDropdown: (
                    <div className="table-filter-search-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            placeholder="输入款号搜索"
                            value={this.state.searchText}
                            onChange={this.onInputChange.bind(this)}
                            onPressEnter={this.onSearch.bind(this)}
                        />
                        <Button type="primary" onClick={this.onSearch}>搜索</Button>
                    </div>
                ),
                filterDropdownVisible: this.state.filterDropdownVisible,
                onFilterDropdownVisibleChange: (visible) => {
                    this.setState({
                        filterDropdownVisible: visible,
                    }, () => this.searchInput.focus());
                },
                filterIcon:(<Icon className="table-filter-search-icon" type="search" style={{ color: this.state.filtered ? '#36b3b3' : '#aaa' }} />),
                render:(text, record, index) =>{
                    return <span className="" ref={"styleNo"}>{record.styleNo}</span>
                }
            },*/
            {
                title:"品名",
                dataIndex: 'productName',
                key: 'productName',
                width: 200,
                render:(text, record, index) =>{
                    // console.log(record.productName);
                    return <span className="" ref={"productName"}  title={record.productName}>{record.productName}</span>
                }
            },
            {
                title: '颜色',
                dataIndex: 'color',
                key: 'color',
                width:100,
                render:(text, record, index) =>{
                    return <span className="" ref={"color"}>{record.color}</span>
                }

            },
            {
                title: '描述/规格',
                dataIndex: 'description',
                key: 'description',
                width: 150,
                render:(text, record, index) =>{
                    return <span className="" ref={"description"}>{record.description}</span>
                }
            },
            {
                title: '尺码',
                key: 'size',
                dataIndex: 'size',
                width:100,
                render:(text, record, index) =>{
                    return <span className="" ref={"size"}>{record.size}</span>
                }
            },
            {
                title: '数量',
                key: 'quantity',
                dataIndex: 'quantity',
                width:100,
                render:(text, record, index) =>{
                    return <span className="" ref={"quantity"}>{Number(record.quantity)}</span>
                }
            },
            {
                title: '用量/件',
                key: 'dosage',
                dataIndex: 'dosage',
                width:100,
                render:(text, record, index) =>{
                    return <span className="" ref={"dosage"}>{Number(record.dosage).toFixed(3)}</span>
                }
            },
            {
                title: '损耗',
                key: 'consume',
                dataIndex: 'consume',
                width:100,
                render:(text, record, index) =>{
                    return <span className="" ref={"consume"}>{Number(record.consume).toFixed(3)}</span>
                }
            },
            {
                title:"需求数",
                dataIndex: 'needCount',
                key: 'needCount',
                width:100,
                render:(text, record, index) =>{
                    return <span className="" ref={"needCount"}>{Number(record.needCount)}</span>
                }
            },
            {
                title: '单位',
                key: 'prickle',
                dataIndex: 'prickle',
                width:100,
                render:(text, record, index) =>{
                    return <span className="" ref={"prickle"}>{record.prickle}</span>
                }
            },
            {
                title: '用处与位置说明',
                dataIndex: 'partDesc',
                key: 'partDesc',
                width: 200,
                render:(text, record, index) =>{
                    return <span className="" ref={"partDesc"}>{record.partDesc}</span>
                }
            },
        ];
        const rowSelection = {
            selectedRowKeys,//默认选中项
            onChange: (selectedRowKeys, selectedRows) => {
                // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                this.setState({
                    selectedRowKeys:selectedRowKeys,
                    selectedRows:selectedRows,
                })
            },
            getCheckboxProps: record => ({
                disabled: record.purchStatus == '1',    // Column configuration not to be checked
            }),
        };
        let locale = {
            filterTitle: '筛选',
            filterConfirm: '确定',
            filterReset: '重置',
            emptyText: '暂无数据',
        };
        return (
            <div className="materielBom_index_box">
                {orderStatus == 3 ? (
                    <div className="materielBom_set_bombBtn">
                        <span className="materielBom_set_tsp" onClick={this.editMateriel.bind(this,"produceList")}>生成采购订单</span>
                        <span className="materielBom_set_tsp" onClick={this.editMateriel.bind(this,"add")}>添加物料</span>
                        <span className="materielBom_set_tsp" onClick={this.editMateriel.bind(this,"edit")}>编辑</span>
                        <span className="materielBom_set_tsp" onClick={this.editMateriel.bind(this,"delete")}>删除</span>
                        <span className="materielBom_set_tsp" onClick={this.editMateriel.bind(this,"markPurchase")}>标记为已采购</span>
                    </div>
                ):null}
                <Table
                    rowSelection={orderStatus == 3 ? rowSelection : null}
                    columns={columns}
                    dataSource={dataSource}
                    className="order_table materielBom_table table_filter_materiel"
                    pagination={false}
                    style={{width:'100%',marginTop:"0"}}
                    loading={this.state.loading}
                    locale = {locale}
                    scroll={{ x: 914}}
                    rowKey={record =>record.bomId}
                    onChange={this.handleChange}
                />
                <AddMaterielModal
                    ref={"addMaterielBill"}
                    //materielBillData={this.state.materielBillData}
                    orderGoodsList={this.orderGoodsList}
                    addMaterielSuccess={this.addMaterielSuccess.bind(this)}
                    findMaterielBill={this.findMaterielBill.bind(this)}
                />
                <BatchHint ref={"batchHint"} _clickConfirm={this.clickConfirm.bind(this)}/>
            </div>
        )
    }
}
